#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: token.py
@contact: zwb15083976291@163.com
@time: 2021/11/11
"""
import time

import itsdangerous
from itsdangerous import SignatureExpired, BadSignature


class TokenGenerator(object):

    def __init__(self, secret_key, salt, expires_in=None):
        if expires_in:
            self.serializer = itsdangerous.TimedJSONWebSignatureSerializer(secret_key=secret_key, salt=salt,
                                                                           expires_in=expires_in)
        else:
            self.serializer = itsdangerous.TimedJSONWebSignatureSerializer(secret_key=secret_key, salt=salt)

    def encryption_token(self, params_dict: "encryption dict"):
        return self.serializer.dumps(params_dict).decode("utf-8")

    def decrypt_token(self, encryption_token):
        try:
            return True, self.serializer.loads(encryption_token)
        except SignatureExpired as e:
            return False, ("令牌过期", 1)
        except BadSignature as e:
            return False, ("令牌错误", 0)


if __name__ == '__main__':
    token = TokenGenerator("ssfjfdslgnrueisonge*(u9y&*9hujhgnsl", "dsajf", 100).encryption_token(
        dict(name="zwb", password="122345"))
    print(token)
    data = token = TokenGenerator("ssfjfdslgnrueisonge*(u9y&*9hujhgnsl", "dsajf", 100).decrypt_token(
        token)
    print(data)
